package com.lahuan.transaction;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lahuan.demo.entity.AccountRmb;
import com.lahuan.demo.entity.AccountUsd;
import com.lahuan.demo.entity.FrozeAccountRmb;
import com.lahuan.demo.entity.FrozeAccountUsd;
import com.lahuan.demo.service.AccountRmbService;
import com.lahuan.demo.service.AccountUsdService;
import com.lahuan.demo.service.FrozeAccountRmbService;
import com.lahuan.demo.service.FrozeAccountUsdService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.hmily.annotation.HmilyTCC;
import org.dromara.hmily.core.context.HmilyContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;


/**
 * @author lfy
 */
@Component
public class TestTransactionImpl implements TestTransaction {

    @DubboReference(version = "1.0.0", interfaceClass = AccountUsdService.class)
    private AccountUsdService accountUsdService;
    @DubboReference(version = "1.0.0", interfaceClass = AccountRmbService.class)
    private AccountRmbService accountRmbService;

    @DubboReference(version = "1.0.0", interfaceClass = FrozeAccountRmbService.class)
    private FrozeAccountRmbService frozeAccountRmbService;
    @DubboReference(version = "1.0.0", interfaceClass = FrozeAccountUsdService.class)
    private FrozeAccountUsdService frozeAccountUsdService;




    @HmilyTCC(confirmMethod = "confirmTransaction", cancelMethod = "cancelTransaction")
    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void tryTransaction(Long userIdDecRmbAddUsd, Long userIdDecUsdAddRmb, BigDecimal moneyRmb, BigDecimal moneyUsd, String transNo) {
        //冻结
        System.out.println("try");
        accountRmbService.froze(userIdDecRmbAddUsd,moneyRmb,transNo);
        accountUsdService.froze(userIdDecUsdAddRmb,moneyUsd,transNo);

    }



    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void confirmTransaction(Long userIdDecRmbAddUsd, Long userIdDecUsdAddRmb, BigDecimal moneyRmb, BigDecimal moneyUsd, String transNo) {
        System.out.println("confirm");
        accountRmbService.add(userIdDecUsdAddRmb,moneyRmb,transNo);
        accountUsdService.add(userIdDecRmbAddUsd,moneyUsd,transNo);
    }


    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void cancelTransaction(Long userIdDecRmbAddUsd, Long userIdDecUsdAddRmb, BigDecimal moneyRmb, BigDecimal moneyUsd, String transNo) {
        System.out.println("cancel");
        accountRmbService.rollback(userIdDecRmbAddUsd,moneyRmb,transNo);
        accountUsdService.rollback(userIdDecUsdAddRmb,moneyUsd,transNo);
    }
}
